package com.tuliyou.service.impl;

import com.tuliyou.common.util.Result;
import com.tuliyou.common.util.UserHolder;
import com.tuliyou.entity.User;
import com.tuliyou.mapper.RecommendationMapper;
import com.tuliyou.mapper.UserMapper;
import com.tuliyou.service.RecommendationService;
import com.tuliyou.vo.RecommendationVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class RecommendationServiceImpl implements RecommendationService {

    @Resource
    private RecommendationMapper recommendationMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    public Result<List<RecommendationVO>> getRecommendations() {
        // 1.从UserHolder中获取用户id
        Long userId = UserHolder.getUser().getId();
        // 2.根据用户id在users表中查询用户省排（不存在返回错误提示信息），所属省份和选科类型（不存在默认按照河北省，物理组合查询）
        User user = userMapper.selectById(userId);
        Integer provinceRank = user.getProvinceRank();
        if (provinceRank == null) {
            return Result.error("请填写正确的位次");
        }
        String province = user.getProvince();
        if (province == null) {province = "河北";}
        String examType = user.getExamType();
        if (examType == null) {examType = "PHYSICS";}
        // 3.查询最近一年（2025年符合条件是招生数据）
        List<RecommendationVO.Enrollment> enrollments = recommendationMapper.getRecommendations(provinceRank,province,examType);
        // 4.计算每条数据的匹配指标并把数据组装成RecommendationVO对象放入列表中
        // 4.1.创建集合
        List<RecommendationVO> list = new ArrayList<>();
        // 4.2.计算匹配指标
        for(RecommendationVO.Enrollment enrollment : enrollments){
            // 计算排名差值（用户排名 - 专业最低排名）
            int rankDifference = provinceRank - enrollment.getMinRank();
            // 确定匹配度和风险等级
            String matchDegree;
            String safetyLevel;
            if (rankDifference > 500) {
                matchDegree = "冲刺";
                safetyLevel = "高风险";
            } else if (rankDifference >= -1000) {
                matchDegree = "稳妥";
                safetyLevel = "中风险";
            } else {
                matchDegree = "保底";
                safetyLevel = "低风险";
            }
            // 生成推荐理由
            String recommendReason = String.format("您的排名:%d，该专业2025年最低排名:%d，建议%s",
                    provinceRank, enrollment.getMinRank(), matchDegree);
            list.add(new RecommendationVO(enrollment,rankDifference,matchDegree,recommendReason,safetyLevel));
        }
        // 5.对列表进行排序
        // 第一优先级：matchDegree（冲刺 > 稳妥 > 保底），第二优先级：同一匹配度内，按 rankDifference 绝对值升序（更接近的优先

        // 6.结果过滤（控制推荐数量，避免过多）

        // 7.把结果封装成Result对象并返回
        return Result.success(list);
    }
}
